package org.vdab.projects.tasks.client.gui.widgets;

import org.vdab.projects.tasks.client.util.DelayedList;
import org.vdab.projects.tasks.client.util.ICommand;
import org.vdab.projects.tasks.client.util.ICommandWithReturn;
import org.vdab.projects.tasks.client.util.MessageGuard;
import org.vdab.projects.tasks.shared.entities.IBaseEntity;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class EntityListWidget<E extends IBaseEntity<?>, W extends Widget> extends Composite {

	private static EntityListWidgetUiBinder uiBinder = GWT
			.create(EntityListWidgetUiBinder.class);

	interface EntityListWidgetUiBinder extends UiBinder<Widget, EntityListWidget<?,?>> {
	}

	@UiField
	VerticalPanel widgetContainer;
	
	private DelayedList<E> entities;

	public EntityListWidget() {
		MessageGuard.Log("in EntityList ctr.");
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	public void bind(DelayedList<E> boundedList,final ICommandWithReturn<E, W> createWidget) throws Exception{
		this.entities = boundedList;
		entities.onLoadedDo(new ICommand<E>() {
			@Override
			public void execute(E entity) throws Exception {
				W widget = createWidget.execute(entity);
				widgetContainer.add(widget);
			}
		});
	}

	public void clear() {
		this.widgetContainer.clear();		
	}
}
